// pages/userInfo/userInfo.js
import {
  userBehavior
} from "./behavior"
import {uploadImage,updateUserInfo} from "../../api/user"

import {setStorage} from "../../utils/storage"
import {toast} from "../../utils/extendApi"

Page({
  behaviors: [userBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    showUserInfo: {}
  },



  async update(event) {
    const {type} = event
    const {
      name
    } = event.currentTarget.dataset
    let value = event.detail.value || event.detail.avatarUrl || event.detail
    if (typeof value === "object") value = ""
    // 如果修改了头像（则直接向服务器上传）
    if (type === "chooseavatar"){
      const res = await uploadImage(value)
      const {avatarUrl} = JSON.parse(JSON.parse(res.data).data)
      this.setData({
        "showUserInfo.headimageurl": avatarUrl
      })
    }else {
      this.setData({
        [`showUserInfo.${name}`] : value
      })
    }
  },

  // 提交内容
  async submit() {
    const {id, nickname, phone, headimageurl} = this.data.showUserInfo
    if(!nickname || !phone || !headimageurl) {
      toast({title: "信息项不能为空", icon: "error"})
      return
    }
    const {code} = await updateUserInfo({id, nickname, phone, headimageurl})
    // 保存成功
    if (code === 200) {
      setStorage("userInfo", this.data.showUserInfo)
      this.setUserInfo(this.data.showUserInfo)
      toast({title: "保存成功！", icon: "success"})
    }else {
      toast({title: "保存失败！", icon: "error"})
    }
  },

  onShow() {
    // console.log(this.data.userInfo);
    const obj = JSON.parse(JSON.stringify(this.data.userInfo))
    // 重新赋值
    this.setData({
      showUserInfo: obj
    })
  }
})